<template>
  <Row
    :gutter="24"
    v-hasC="{ name: 'v1-base-hospital-index', flag: 'v1/base/hospital/index' }"
  >
    <i-col span="16">
      <Card dis-hover :bordered="false">
        <div class="ivu-tit">医院设置</div>
        <Form
          :label-width="118"
          ref="formInfo"
          :model="infoData"
          :rules="infoRules"
        >
          <FormItem label="医院名称" prop="name">
            <Input placeholder="请输入医院名称" v-model="infoData.name" />
          </FormItem>
          <FormItem label="地址" prop="address">
            <Input placeholder="请输入医院地址" v-model="infoData.address" />
          </FormItem>
          <FormItem label="联系方式" prop="mobile">
            <Input placeholder="请输入医院联系方式" v-model="infoData.mobile" />
          </FormItem>
          <FormItem label="营业时间" prop="business_time">
            <Input
              placeholder="输入营业时间"
              v-model="infoData.business_time"
            />
          </FormItem>
          <FormItem label="医院标签" prop="tag_ids">
            <Select
              v-model="infoData.tag_ids"
              filterable
              multiple
              allow-create
              @on-create="handleCreate"
              @on-change="changeSelect"
            >
              <Option
                v-for="item in tagList"
                :value="item.label"
                :key="item.label"
                :disabled="+item.disabled === 1 ? false : true"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="形象图" prop="path" :rules="infoRules.path">
            <div class="imageUpdate">
              <Upload
                multiple
                ref="upload"
                v-model="infoData.path"
                :show-upload-list="false"
                :action="requestAction"
                :format="['jpg', 'jpeg', 'png']"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
              >
                <Button
                  type="primary"
                  class="ivu-ml-8 ivu-mr-8"
                  :loading="loadingUpload"
                  >{{ loadingUpload ? "上传中..." : "上传" }}</Button
                >
              </Upload>
              <Button type="success" @click="showImgModel = true">选择</Button>
            </div>
            <div
              class="demo-upload-list"
              v-for="(item, i) in uploadList"
              :key="i"
            >
              <div>
                <img :src="item" fit="cover" width="100%" height="100%" />
                <div class="demo-upload-list-cover">
                  <Icon type="ios-eye-outline" @click="handleView(item)"></Icon>
                  <Icon
                    type="ios-trash-outline"
                    @click="handleRemove(item)"
                  ></Icon>
                </div>
              </div>
            </div>
          </FormItem>
          <FormItem label="医院概况" prop="introduce">
            <ckeditor
              :editor="editor"
              v-model="infoData.introduce"
              :config="editorConfig"
            ></ckeditor>
          </FormItem>
        </Form>
      </Card>
    </i-col>
    <i-col span="8">
      <Card dis-hover :bordered="false">
        <div class="ivu-tit">小程序设置</div>
        <Form ref="formIp" :model="ipData" :rules="ipRules">
          <FormItem label="微信小程序AppId" prop="appid">
            <Input placeholder="请输入微信小程序AppId" v-model="ipData.appid" />
          </FormItem>
          <FormItem label="微信小程序AppSecret" prop="appsecret">
            <Input
              placeholder="请输入微信小程序AppSecret"
              :rows="8"
              v-model="ipData.appsecret"
            />
          </FormItem>
          <FormItem label="微信视频号ID" prop="video_id">
            <Input
              placeholder="请输入微信视频ID"
              :rows="8"
              v-model="ipData.video_id"
            />
          </FormItem>
        </Form>
      </Card>
      <!-- <Card dis-hover :bordered="false" class="ivu-mt-16">
        <div class="ivu-tit">
          模块首页设置
          <Tooltip content="模块是否在首页展示开关">
            <Icon class="ivu-ml-8 v-bold" type="ios-help-circle-outline" />
          </Tooltip>
        </div>
        <Form :label-width="118" :model="formData">
          <FormItem label="医生">
            <Switch v-model="formData.doctor_show" />
          </FormItem>
          <FormItem label="活动">
            <Switch v-model="formData.activity_show" />
          </FormItem>
          <FormItem label="视频">
            <Switch v-model="formData.video_show" />
            <Tooltip content="视频模块开启，请先设置视频号ID">
              <Icon class="ivu-ml-8 v-bold" type="ios-help-circle-outline" />
            </Tooltip>
          </FormItem>
        </Form>
      </Card> -->
      <Card dis-hover :bordered="false" class="ivu-mt-16">
        <div class="ivu-tit">挂号设置</div>
        <Form :label-width="118" :model="formData">
          <FormItem label="号间隔时间">
            <InputNumber
              v-model="formData.time_interval"
              :precision="0"
              :min="5"
              :max="120"
              :step="5"
            />分钟
          </FormItem>
        </Form>
      </Card>
    </i-col>
  </Row>
  <FooterToolbar>
    <Button
      type="primary"
      @click="saveSubmit"
      size="large"
      :loading="loading"
      v-hasC="{
        name: 'v1-base-hospital-update-hospital',
        flag: 'v1/base/hospital/update-hospital',
      }"
      >保存</Button
    >
  </FooterToolbar>
  <Modal v-model="imgVisible" footer-hide>
    <p slot="header">查看大图</p>
    <img :src="viewingImg" style="width: 100%; object-fit: cover" />
  </Modal>
  <glo-check v-model="showImgModel" @getImgArr="getImgArr" :number="imgLimit" />
</template>
<script>
// import ClassicEditor from '@/components/ckeditor/ckeditor'
// import ClassicEditor from '@ckeditor/ckeditor5-editor-classic/src/classiceditor';
import ClassicEditor from "@ckeditor/ckeditor5-build-classic"
import CKEditor from "@ckeditor/ckeditor5-vue"
const ckUpload = require("../../../libs/ckeditorUplodImg5")
import { infoHospital, updateHospital } from "@/api/set"
import Setting from "@/setting"
import util from "@/libs/util"
import { Message } from 'view-ui-plus'
export default {
  name: "modalName",
  components: { ckeditor: CKEditor.component },
  data () {
    return {
      showImgModel: false,
      loading: false,
      loadingUpload: false,
      editor: ClassicEditor,
      editorConfig: {
        extraPlugins: [ckUpload.MyCustomUploadAdapterPlugin],
        fullscreen: {
          // 点击按钮后会执行的回调函数
          handler: () => {
            // this.modalstatus = true;
          },
        },
        material: {
          // 点击按钮后会执行的回调函数
          handler: () => {
            this.askData()
            this.modalstatus = true
            this.showlink = true
            this.img = ""
            this.isDobule = true
          },
        },
        mediaEmbed: {
            providers: [{
            name: 'myprovider',
            url: [
              /^lizzy.*\.com.*\/media\/(\w+)/,
              /^www\.lizzy.*/,
              /^.*/
            ],
            html: match => {
              //获取媒体url
              const input = match['input'];
            //console.log('input' + match['input']);
              return (
                '<div style="position: relative; padding-bottom: 100%; height: 0; padding-bottom: 70%;">' +
                  `<iframe src="${input}" ` +
                    'style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" ' +
                    'frameborder="0" allowtransparency="true" allow="encrypted-media">' +
                  '</iframe>' +
                '</div>'
              );
            }
          }]
        }
      },
      value: "",
      dateValue: "2022-09-08 06:05:00",
      infoData: {
        id: "",
        name: "",
        address: "",
        mobile: "",
        business_time: "",
        tag_ids: [],
        introduce: "",
        path: [],
      },
      baseUrl: Setting.request.apiBaseURL,
      infoRules: {
        name: [{ required: true, message: "请输入医院名称", trigger: "bulr" }],
        address: [{ required: true, message: "请输入地址", trigger: "bulr" }],
        mobile: [
          { required: true, message: "请输入医院联系方式", trigger: "bulr" },
          // { message: '请填写正确的医院联系方式', pattern: /^1[3456789]\d{9}$/ }
        ],
        business_time: [
          { required: true, message: "请输入营业时间", trigger: "bulr" },
        ],
        tag_ids: [
          {
            required: true,
            message: "请选择医院标签",
            trigger: "change",
            type: "array",
          },
        ],
        introduce: [
          { required: true, message: "请输入医院概况", trigger: "bulr" },
        ],
        path: [
          {
            required: true,
            message: "请选择图片",
            trigger: "bulr,change",
            type: "array",
          },
        ],
      },
      ipData: {
        appid: "",
        appsecret: "",
        video_id: "",
      },
      ipRules: {
        appid: [
          { required: true, message: "请输入微信小程序APPId", trigger: "bulr" },
        ],
        appsecret: [
          {
            required: true,
            message: "请输入微信小程序AppSecret",
            trigger: "bulr",
          },
        ],
      },
      formData: {
        time_interval: 5,
        // doctor_show: true,
        // activity_show: true,
        // video_show: true,
      },
      uploadList: [],
      tagList: [],
      model: "",
      model1: [],
      viewingImg: "",
      imgVisible: false,
      tag_ids: [],
      requestAction: "",
    }
  },
  mounted () {
    this.requestAction =
      this.baseUrl +
      `/v1/upload/images?auth_access_token=${util.cookies.get(
        "token"
      )}&auth_project_id=${localStorage.getItem('currentProject')}`
    this.getinfo()
  },
  methods: {
    handleView (item) {
      // console.log(item);
      this.viewingImg = item
      this.imgVisible = true
    },
    handleRemove (item) {
      this.$Modal.confirm({
        title: "提示",
        content: "确定删除文件?",
        onOk: () => {
          this.uploadList.splice(this.uploadList.indexOf(item), 1)
          this.infoData.path.splice(this.infoData.path.indexOf(item), 1)
        },
      })
    },
    getImgArr (arr) {
      this.uploadList = [...this.uploadList, ...arr]
    },
    //获取基础设置
    getinfo () {
      infoHospital().then((res) => {
        this.infoData = {
          id: res.id,
          name: res.name,
          address: res.address,
          mobile: res.mobile,
          business_time: res.business_time,
          tag_ids: res.tag_names ? res.tag_names.split(",") : [],
          introduce: res.introduce,
          path: res.path.split(","),
        }
        this.ipData = {
          appid: res.appid,
          appsecret: res.appsecret,
          video_id: res.video_id,
        }
        this.formData = {
          time_interval: res.time_interval * 1,
          // doctor_show: +res.doctor_show === 1 ? true : false,
          // activity_show: +res.activity_show === 1 ? true : false,
          // video_show: +res.video_show === 1 ? true : false,
        }
        this.tagList = res.tag_list
        this.uploadList = res.path.split(",")
      })
    },
    handleBeforeUpload (a) {
      const check = this.uploadList.length < 36
      if (!check) {
        this.$Notice.warning({
          title: "最多可以上传36张.",
        })
      } else {
        this.loadingUpload = true
      }
      return check
    },
    //保存
    saveSubmit () {
      this.loading = true
      const rule1 = new Promise((resolve, reject) => {
        this.$refs.formInfo.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            this.loading = false
            // reject('error submit!!')
            // console.log("error submit!!");
            return false
          }
        })
      })
      const rule2 = new Promise((resolve, reject) => {
        this.$refs.formIp.validate((valid) => {
          if (valid) {
            resolve()
          } else {
            this.loading = false
            // console.log("error submit!!");
            return false
          }
        })
      })
      Promise.all([rule1, rule2]).then(() => {
        const params = {
          id: this.infoData.id,
          name: this.infoData.name,
          address: this.infoData.address,
          mobile: this.infoData.mobile,
          business_time: this.infoData.business_time,
          tag: this.tag_ids,
          path: this.uploadList.length > 0 ? this.uploadList.join(",") : "",
          introduce: this.infoData.introduce,
          appid: this.ipData.appid,
          appsecret: this.ipData.appsecret,
          video_id: this.ipData.video_id,
          // doctor_show: this.formData.doctor_show === true ? 1 : 0,
          // activity_show: this.formData.activity_show === true ? 1 : 0,
          // video_show: this.formData.video_show === true ? 1 : 0,
          time_interval: this.formData.time_interval,
        }
        updateHospital(params)
          .then((res) => {
            this.$Message.success("编辑成功")
            this.loading = false
            this.getinfo()
          })
          .catch(() => {
            this.loading = false
          })
        // alert("submit!");
      })
    },
    changeSelect (val) {
      if (val.length > 3) {
        this.$Message.warning("标签不能超过三个~")
        val.splice(3, 1)
        return
      }
      // console.log(val,'val')
      let arr = []
      if (val.length > 0) {
        this.tagList.forEach((item) => {
          val.forEach((it) => {
            if (item.label == it) {
              arr.push({ id: item.value, name: item.label })
            }
          })
        })
        this.tag_ids = [...new Set(arr)]
      } else {
        this.tag_ids = []
      }
      // console.log(this.tag_ids,'this.infoData.tag_ids')
      // if(this.infoData.tag_ids.length>=3){
      //     this.$Message.error('最多选择3个标签')
      // }
    },
    handleCreate (val) {
      this.tagList.push({
        value: "0",
        label: val,
        disabled: "1",
      })
      this.tag_ids.push({ id: "0", name: val })
      // console.log(this.tag_ids,'this.tag_ids')
    },
    handleUploadSuccess (response) {
      // this.uplodloading = false;
      const url = []
      response.data.image_url.forEach((e) => {

        url.push(e)

        if (this.uploadList.length < 36) {

          this.uploadList.push(`${response.data.host}${e}`)
        } else {
          Message.warning('数量不能超过36')
        }
        this.loadingUpload = false
      });
      (this.infoData.path = url), console.log(this.uploadList, "up")
    },
    handleUploadError (error, file, fileList) {
      // this.uplodloading = false;
      this.$Message.error(error)
    },
  },
  computed: {
    imgLimit () {
      return 36 - this.uploadList.length
    },
  }
};
</script>
<style lang='less' scoped>
/deep/ .ck-editor__editable {
  height: 220px;
}
.ivu-tit {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 12px;
}
.imageUpdate {
  display: flex;
}
.v-bold {
  font-weight: bold;
  font-size: 16px;
}
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>
